/*******************************************************************************
 * Copyright 2011 Towee.net
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package net.towee.client.com.repo.view;

import java.util.HashMap;
import java.util.Map;

import net.towee.client.com.repo.presenter.RepositoryExplorerPresenter.Display;
import net.towee.client.i18n.ToweeConstants;
import net.towee.client.resources.ClientResource;
import net.towee.client.widgets.LeftTabsWidget;
import net.towee.client.widgets.ListItemWidget;
import net.towee.model.group.GroupIdentity;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class RepositoryExplorerView extends LeftTabsWidget implements Display, HasSelectionHandlers<GroupIdentity> {
	private final ToweeConstants constants;

	// Map for tree children
	private final Map<String, Widget> groups;

	@Inject
	public RepositoryExplorerView(ToweeConstants constants, ClientResource resource) {
		super(resource);
		this.constants = constants;

		groups = new HashMap<String, Widget>();
	}

	@Override
	public void addGroup(GroupIdentity identity) {
		ListItemWidget item = (ListItemWidget) addTab(identity.getPrintName());
		groups.put(identity.getId(), item);
		
		item.setLayoutData(identity);
		item.addStyleName( resource.css().repoGroupItem() );
	}
	
	@Override
	public void onClick(ClickEvent event){
		super.onClick(event);
		
		// Fire selection event
		SelectionEvent.fire(this, (GroupIdentity)(((Widget)event.getSource()).getLayoutData()) );
	}

	@Override
	public void removeGroup(GroupIdentity identity) {
		if(groups.containsKey(identity.getId())) {
			groups.get( identity.getId() ).removeFromParent();
			groups.remove( identity.getId() );
		}
	}

	@Override
	public HandlerRegistration addSelectionHandler(SelectionHandler<GroupIdentity> handler) {
		return addHandler(handler, SelectionEvent.getType());
	}

	@Override
	public HasSelectionHandlers<GroupIdentity> getSelector() {
		return this;
	}

	@Override
	public void selectGroup(GroupIdentity identity) {
		selectTab( groups.get( identity.getId() ) );
	}
}
